import java.util.Arrays;

public class DoublePointer {

//    删除有序数组中的重复项 (使每个元素 只出现一次 不使用额外空间)
    public static void main1(String[] args) {
        int[] array = new int[]{1,2,2,3,3,4,5};
        System.out.println(removeDuplicates(array));//5



        int[] array2 = new int[]{};
        System.out.println(array2.length);//0
        int[] array3 = null;
//        System.out.println(array3.length); error   NullPointerException
    }

//    方法1
    public static int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int slow = 0;
        int fast = 1;
        while (fast < nums.length) {
            if (nums[slow] == nums[fast]) {
                fast++;
            }else {
                nums[++slow] = nums[fast++];
            }
        }
        return slow+1;
    }

//  方法2  好理解下面那题
    public static int removeDuplicates2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int slow = 0;
        for (int fast = 1; fast < nums.length; fast++) {
            if (nums[slow] != nums[fast]) {
                nums[slow+1] = nums[fast];
                slow++;
            }

        }
        return slow+1;
    }

//    删除有序数组中的重复项2 (使得出现次数超过两次的元素只出现两次 ，返回删除后数组的新长度。 不使用额外空间)
    public static int removeDuplicates3(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int slow = 0;
        for (int fast = 1; fast < nums.length; fast++) {
            if (nums[slow] != nums[fast]) {
                nums[slow+2] = nums[fast];
                slow++;
            }

        }
        return slow+2;
    }





//    寻找数组的中心下标
//    1.
    public int pivotIndex(int[] nums) {
        if (nums == null) return 0;
        int rightTotal = Arrays.stream(nums).sum();//数组总和
        int leftTotal = 0;//从最左边开始计数
        for (int i = 0; i < nums.length; i++) {
            leftTotal += nums[i];
            if (leftTotal == rightTotal) {
                return i;
            }
            rightTotal -= nums[i];
        }
        return -1;
    }
//    2.
    public int pivotIndex2(int[] nums) {
        if (nums == null) return 0;
        int total = Arrays.stream(nums).sum();//数组总和
        int sum = 0;//从最左边开始计数
        for (int i = 0; i < nums.length; i++) {
            if (2*sum + nums[i] == total) {
                return i;
            }
            sum += nums[i];//再判断之后
        }
        return -1;
    }
}
